import React, { useState, useEffect } from "react";
import { Carousel, Card, Row, Col, Button, message} from "antd";
import LeftOutlined from "@ant-design/icons/LeftOutlined";
import RightOutlined from "@ant-design/icons/RightOutlined";
import apps from "./apps";
const { Meta } = Card;
import "./App.css";

const CustomPrevArrow = (props: any) => {
  const { onClick, appsSize } = props;
  return (
    <div
      onClick={onClick}
      style={{ position: "absolute", top: "38%", left: 0, zIndex: 1 }}
    >
      <Button
        type="primary"
        shape="circle"
        icon={<LeftOutlined />}
        className="app-arrow-btn"
      />
    </div>
  );
};

const CustomNextArrow = (props: any) => {
  const { onClick } = props;
  return (
    <div
      onClick={onClick}
      style={{ position: "absolute", top: "38%", right: 0, zIndex: 1 }}
    >
      <Button
        type="primary"
        shape="circle"
        icon={<RightOutlined />}
        className="app-arrow-btn"
      />
    </div>
  );
};

const handleGetAppsIndex = async (messageApi: any) => {
  const headers = {
    'Content-Type': 'application/json',
  };
  try {
    const response = await fetch('/cgi-bin/luci/admin/apps-index/api/apps-index.lua', {
      method: 'GET',
      headers: headers,
    });

    if (!response.ok) {
      throw new Error(response.statusText);
    }

    if (!response.body) return;

    const responseText = await response.text();
    const responseObject = JSON.parse(responseText);
    if(!responseObject.success){
      messageApi.warning(responseObject.msg);
    }{
      return responseObject.data;
    }
  } catch (error) {
    messageApi.error(error);
  }
};

const jumpToApp=(appsIndex: any)=>{
  window.location.href=appsIndex.entrypoint;
};

function App() {
  const [currentSlide, setCurrentSlide] = useState(0); // Define currentSlide state
  const [appsIndex, setAppsIndex] = useState<any[]>([]);
  const [messageApi, contextHolder] = message.useMessage();
  const appsPerPage = 9; // Updated to display 9 apps per page
  const totalPages = Math.ceil(apps.length / appsPerPage);
  const pages = Array.from({ length: totalPages }, (_, index) => index);

  const handleSlideChange = (slideIndex: number) => {
    setCurrentSlide(slideIndex); // Update currentSlide state
  };

  useEffect(() => {
    const fetchData = async () => {
      const data = await handleGetAppsIndex(messageApi);
      setAppsIndex(data);
    };
    fetchData();
  }, []);

  const shouldShowArrows = appsIndex.length > appsPerPage; // Condition to show arrows

  return (
    <div className="App" style={{ overflowY: "hidden" }}>
      {contextHolder}
      <Carousel
        dots={false}
        arrows={true}
        adaptiveHeight={true}
        fade={false}
        prevArrow={shouldShowArrows ? <CustomPrevArrow /> : <></>} // Conditionally render arrows
        nextArrow={shouldShowArrows ? <CustomNextArrow /> : <></>}
        afterChange={handleSlideChange}
        className="app-carousel"
        draggable={shouldShowArrows}
      >
        {pages.map((page, pageIndex) => (
          <div key={pageIndex} className="app-grid">
            <Row gutter={[16, 16]} className="app-row">
              {appsIndex
                .slice(pageIndex * appsPerPage, (pageIndex + 1) * appsPerPage)
                .map((app, appIndex) => (
                  <Col key={appIndex} xs={24} sm={24} md={8} lg={8} xl={8}>
                    <Card
                      className="app-item"
                      onClick={()=>jumpToApp(app)}
                      cover={
                        <div
                          style={{
                            display: "flex",
                            justifyContent: "space-between",
                            alignItems: "center",
                          }}
                        >
                          <div>
                            <img
                              alt="example"
                              src={app.icon}
                              style={{
                                width: 50,
                                height: 50,
                                marginInlineStart: 10,
                              }}
                            />
                          </div>
                          <div style={{ paddingRight: 10 }}>
                            <span style={{ color: '#ffffff', fontSize: 14 ,fontWeight: 'bold'}}>
                              {app.vendor}-{app.version}
                            </span>
                          </div>
                        </div>
                      }
                    >
                      <Meta title={app.title} description={app.description} />
                    </Card>
                  </Col>
                ))}
            </Row>
          </div>
        ))}
      </Carousel>
    </div>
  );
}

export default App;
